//
//  PettyImageViewController.m
//  WuLi
//
//  Created by Gollum on 16/9/9.
//  Copyright © 2016年 Gollum. All rights reserved.
//

#import "PettyImageViewController.h"
#import "NetworkTool.h"
#import "RootRankDetailAttached.h"
#import "RootRankDetailDataModel.h"
#import "RootRankDetailDebuginfoModel.h"
#import "RootRankDetailModel.h"
#import "RootRankDetailNewsimageinfolist.h"
#import "YYAnimationView.h"

//评论的model
#import "DiscussModel.h"
#import "DiscussData.h"
#import "DiscussAttached.h"

//tool
#import "BulletManager.h"
#import "BulletView.h"
#import "UIView+Frame.h"
#import "DiscussTableViewCell.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"

#import "JHMacro.h"

#define kDiscussTableViewCellReuse @"DiscussCell"


@interface PettyImageViewController ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate>
@property (nonatomic,strong)RootRankDetailModel *rankData;
@property (nonatomic,strong)DiscussModel *discussData;
@property (nonatomic,strong)BulletManager *bulletManager;
@property (nonatomic,strong)NSMutableArray <DiscussData *>*discussDataArray;
@property (nonatomic,strong)NSMutableArray *bulletArray;


@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;

@property (nonatomic,strong)UIActivityIndicatorView *action;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,copy)NSString *urlString;
@property (nonatomic,copy)NSMutableString *str1;
@property (nonatomic,copy)NSMutableString *str2;

@property (nonatomic,strong)UIView *bgView;
@property (nonatomic,strong)UIImageView *imageView;


@end

@implementation PettyImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

   _dataArray  = [NSMutableArray array];
    self.discussDataArray = [NSMutableArray array];
    self.bulletArray = [NSMutableArray array];

    self.bulletManager = [[BulletManager alloc] init];
    __weak PettyImageViewController *myself = self;
    self.bulletManager.generateBulletBlock = ^(BulletView *bulletView) {
        
        [myself addBulletView:bulletView];
    };
    [_tableView registerNib:[UINib nibWithNibName:@"DiscussTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kDiscussTableViewCellReuse];
    
    _tableView.rowHeight = 100;
    _webView.scrollView.bounces = NO;
    _webView.delegate = self;
    // Do any additional setup after loading the view from its nib.
    //    刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self handleData];
            
            [_tableView.mj_header endRefreshing];
            
        });
    }];
    
    
    [self.tableView.mj_header beginRefreshing];
    
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self handleDiscussData];

            [_tableView.mj_footer endRefreshing];
        });
    }];
    

    
    
    
}

- (void)handleData{
    
    
    NSString *urlString = _detailString;
    
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.3.1 (agent:s;channel:wandoujia;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzExODgxOTgzODY=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com"};
    [NetworkTool GET:urlString andBody:nil andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
        
//        NSLog(@"-----------------------------%@",result);
        _rankData = [RootRankDetailModel modelWithDic:result];
        [_dataArray addObject:_rankData];
        
        //            NSURL *url = [NSURL URLWithString:_rankData.data.newsImageInfoList[0].src];
        //            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        //            [_webView loadRequest:request];
        //        [_webView loadHTMLString:_rankData.data.content baseURL:nil];
        
        
        _urlString = _rankData.data.content.mutableCopy;
        
        for (int i = 1; i <= _rankData.data.newsImageInfoList.count; i ++) {
            
            _str1 = [NSString stringWithFormat:@"${{%d}}$",i].mutableCopy;
            _str2 = _rankData.data.newsImageInfoList[i - 1].src.mutableCopy;
            NSString *strOne = @"<img width=\"100%\" src=\"";
            NSString *strTwo = @"\"/>";
            NSString *str = [[strOne stringByAppendingString:_str2] stringByAppendingString:strTwo];
            _urlString = [_urlString stringByReplacingOccurrencesOfString:_str1 withString:str].mutableCopy;
        }
        
        [_webView loadHTMLString:_urlString baseURL:nil];
//        _titleLabel.text = _rankData.data.title;
//        NSURL *url = [NSURL URLWithString:_rankData.data.originIcon];
//        [_originalImage sd_setImageWithURL:url];
//        _originalName.text = _rankData.data.originName;
        
        [_tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
}

- (void)handleDiscussData{
    NSString *newsId = _rankData.data.newsId;
    NSString *str1 = @"http://211.151.51.100/v3/comment/list?messageId=";
    NSString *str2 = @"&messageType=NEWS&engine=&commentId=&pageIndex=0&pageSize=20&rangeType=1";
    NSString *urlString = [[str1 stringByAppendingString:newsId] stringByAppendingString:str2];
    
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.3.1 (agent:s;channel:wandoujia;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzExODgxOTgzODY=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com"};
    [NetworkTool GET:urlString andBody:nil andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
        
        NSLog(@"DiscussData:%@",result);
        _discussData = [DiscussModel modelWithDic:result];
        _discussDataArray = _discussData.data.mutableCopy;
        NSLog(@"~~~~~~%ld",_discussData.data.count);
        
        [_tableView reloadData];
        
        for (int i = 0; i < _discussDataArray.count; i ++) {
            [_bulletArray addObject:_discussDataArray[i].content];
        }
        NSLog(@"-=-=-=-=-=-==-=%ld",_bulletArray.count);
        _bulletManager.allComments = _bulletArray;
        [_bulletManager start];
        
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    
}



- (IBAction)handleBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)shareButton:(id)sender {
    [self showAnimationView];
}
- (void)showAnimationView
{
    NSArray *imgNameArray = @[@"朋友圈"
                              ,@"微信"
                              ,@"QQ"
                              ,@"QQ空间"
                              ,@"新浪微博"
                              ,@"复制链接"
                              , @"收藏-1"
                              ,@"字体设置"
                              ,@"举报"
                              ,@"夜间模式"
                              ];
    
    NSArray *titleArray = @[@"朋友圈"
                            ,@"微信"
                            ,@"QQ"
                            ,@"QQ空间"
                            ,@"新浪微博"
                            ,@"复制链接",
                            @"收藏",
                            @"字体设置",
                            @"举报",
                            @"夜间模式"
                            ];
    YYAnimationView *animationView = [[YYAnimationView alloc] initImageNameArray:imgNameArray withItmeTitleArray:titleArray];
    animationView.lineItmeNumber = 3;
    animationView.itmeSize = CGSizeMake(100, 100);
    animationView.itmeTitleFont = [UIFont systemFontOfSize:15];
    [animationView addButtonItmeToAnimationView];
    [animationView showAnimationView];
    animationView.yyAnimationButtonItmeClick = ^( NSInteger tags){
        NSLog(@"%ld",(long)tags);

        if (tags == 6) {
            [self handleDataCollected];
        }
    };
}

- (void)handleDataCollected{
    
    //http://211.151.51.100/v1/news/collect
    
    NSString *urlString = @"http://211.151.51.100/v1/news/collect";
    
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.4.0 (agent:s;channel:pphl;credential:e1MyMDIwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDA5NzE2NTcwLTU0OTIyZjhiZTV9QDE0NzQwNzgyODczNjU=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com",@"Content-Type":@"application/json;charset=UTF-8"};
    NSString *str1 = @"{\"parentType\": \"";
    NSString *str2 = @"\",\"newsEngineType\": \"";
    NSString *str3 = @"\",\"parentId\": \"";
    NSString *str4 = @"\",\"newsId\": \"";
    NSString *str5 = @"\",\"layoutType\": \"";
    NSString *str6 = @"\",\"newsType\": \"";
    NSString *str7 = @"\"}";
    
    NSString *bodyStr = [[[[[[[[[[[[str1 stringByAppendingString:_parentType] stringByAppendingString:str2] stringByAppendingString:_newsEngineType] stringByAppendingString:str3] stringByAppendingString:_parentId] stringByAppendingString:str4] stringByAppendingString:_newsId] stringByAppendingString:str5] stringByAppendingString:_layoutType] stringByAppendingString:str6] stringByAppendingString:_newsType] stringByAppendingString:str7];
    
    //    NSString *bodyString = @"{\"parentType\": \"CHANNEL\",\"newsEngineType\": \"RECOMMEND\",\"parentId\": \"81001\",\"newsId\": \"cmsevztxmvjet\",\"layoutType\": \"SINGLE\",\"newsType\": \"NEWS\"}";
    
    [NetworkTool POST:urlString andBody:bodyStr andBodyStyle:JHBodyString andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
        
        NSLog(@"------------------++++++++++++%@",result);
        //        _rankModel = [RankModel modelWithDic:result];
        //        _recommend = [RecommendModel modelWithDic:result];
        
        if ([[result objectForKey:@"message"]isEqualToString:@"ok"]) {
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okCtrl = [UIAlertAction actionWithTitle:@"OK"style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * _Nonnull action){
                                                           }];
            //step 3 action
            [alertController addAction:okCtrl];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"收藏失败" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        
        
        
    } andFailureBlock:^(NSError *error) {
        
        NSLog(@"请求失败");
        
    }];
    
}






- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _discussDataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DiscussTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDiscussTableViewCellReuse];
    NSURL *url = [NSURL URLWithString:_discussData.data[indexPath.row].portrait];
    [cell.userImage sd_setImageWithURL:url];
    cell.userName.text = _discussData.data[indexPath.row].nickName;
    cell.contentLabel.text = _discussData.data[indexPath.row].content;
    cell.timeLabel.text = [NSString stringWithFormat:@"%lld",_discussData.data[indexPath.row].createTime];
    cell.likeLabel.text = [NSString stringWithFormat:@"%ld",_discussData.data[indexPath.row].totalLikeCount];
    
    
    return cell;
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return @"全部评论";
    
}

//界面蒙版
- (void)viewWillAppear:(BOOL)animated{
    
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor lightGrayColor]];
    [view setAlpha:0.9];
    [self.view addSubview:view];
    self.action = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];// 指定进度轮大小
    self.action.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [self.action setCenter:view.center];// 指定进度轮中心点
    [self.action setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];// 设置进度轮显示类型
    [view addSubview:self.action];
    [self.action startAnimating];
    
}





//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [self.action stopAnimating];
//    UIView *view = (UIView *)[self.view viewWithTag:108];
//    [view removeFromSuperview];
//    
//    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//    CGRect frame = webView.frame;
//    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
//    //    [webView sizeThatFits:webView.frame.size];
//    _headerView.JH_height =  webView.JH_height;
//    
//    _tableView.tableHeaderView = _headerView;
//    
//    
//    
//}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.action stopAnimating];
    UIView *view = (UIView *)[self.view viewWithTag:108];
    [view removeFromSuperview];
    
    
    //    NSString *str1 = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '";
    //    NSString *str2 = @"%'";
    //    NSString *set = [[str1 stringByAppendingString:[NSString stringWithFormat:@"%f",_webFontSize]] stringByAppendingString:str2];
    //
    //    [webView stringByEvaluatingJavaScriptFromString:set];//修改百分比即可
    //    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '40%'"];//修改百分比即可
    
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    CGRect frame = webView.frame;
    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    //    [webView sizeThatFits:webView.frame.size];
    _headerView.JH_height =  webView.JH_height ;
    
    _tableView.tableHeaderView = _headerView;
    
    //    [webView reload];
    
    
    //调整字号
//    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '95%'";
//    [webView stringByEvaluatingJavaScriptFromString:str];
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    //调用js方法
    NSLog(@"---调用js方法--%@  %s  jsMehtods_result = %@",self.class,__func__,resurlt);
    
    
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    //    NSLog(@"requestString is %@",requestString);
    
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        //        NSLog(@"image url------%@", imageUrl);
        
        if (_bgView) {
            //设置不隐藏，还原放大缩小，显示图片
            _bgView.hidden = NO;
            _imageView.frame = CGRectMake(10, 10, SCREEN_WIDTH-100, SCREEN_HEIGHT -110);
            
            [_imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"default_image"]];
        }
        else
            [self showBigImage:imageUrl];//创建视图并显示图片
        
        return NO;
    }
    return YES;
}
#pragma mark 显示大图片
-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景，使其背后内容不可操作
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [_bgView setBackgroundColor:[UIColor colorWithRed:0.3
                                                green:0.3
                                                 blue:0.3
                                                alpha:0.7]];
    [self.view addSubview:_bgView];
    
    //创建边框视图
    //    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20, 240)];
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, SCREEN_HEIGHT - 100)];
    
    //将图层的边框设置为圆脚
    borderView.layer.cornerRadius = 8;
    borderView.layer.masksToBounds = YES;
    //给图层添加一个有色边框
    borderView.layer.borderWidth = 8;
    borderView.layer.borderColor = [[UIColor colorWithRed:0.9
                                                    green:0.9
                                                     blue:0.9
                                                    alpha:0.7] CGColor];
    [borderView setCenter:_bgView.center];
    [_bgView addSubview:borderView];
    
    //创建关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    //    closeBtn.backgroundColor = [UIColor lightGrayColor];
    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setFrame:CGRectMake(borderView.frame.origin.x+borderView.frame.size.width-20, borderView.frame.origin.y-6, 26, 27)];
    [_bgView addSubview:closeBtn];
    
    //创建显示图像视图
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(borderView.frame)-20, CGRectGetHeight(borderView.frame)-20)];
    _imageView.userInteractionEnabled = YES;
    //    [_imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [borderView addSubview:_imageView];
    
    //添加捏合手势
    [_imageView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
    
}
//关闭按钮
-(void)removeBigImage
{
    _bgView.hidden = YES;
}

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
{
    //缩放:设置缩放比例
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;
}
//添加弹幕
- (void)addBulletView:(BulletView *)bulletView {
    bulletView.frame = CGRectMake(CGRectGetWidth(self.view.frame)+50, CGRectGetHeight(self.view.frame) - 200 + 40 * bulletView.trajectory, CGRectGetWidth(bulletView.bounds), CGRectGetHeight(bulletView.bounds));
    [self.view addSubview:bulletView];
    [bulletView startAnimation];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
